package fms.util;

import java.io.*;

import org.apache.log4j.Logger;

/**
 * Created with IntelliJ IDEA.
 * To change this template use File | Settings | File Templates.
 */
public class FileUtil {
    public static Logger logger = Logger.getLogger(FileUtil.class);
    // 飞行计划字符串编码方式
    private static final String StrEncoding =  "UTF-8";

    // 通过内容判断文件类型是否为XML
    // fileName文件全路径，为本地方式解析使用
    public static boolean IsXmlDocByContext(String fileName) {
        FileReader read = null;
        BufferedReader br = null;
        try {
//            System.out.println(fileName);
            read = new FileReader(fileName);
            br = new BufferedReader(read);
            String row;
            if (!ObjectUtil.isBlank(row = br.readLine())) {
//                System.out.println(row);
                if (row.substring(0, 5).equals("<?xml") && row.substring(row.length() - 2, row.length()).equals("?>")) {
                    read.close();
                    br.close();
                    return true;
                }
            }
            read.close();
            br.close();
        } catch (FileNotFoundException e) {
            //文件未写完，无法打开文件，不处理
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (read != null) read.close();
                if (br != null) read.close();
            } catch (IOException ex) {
                logger.error("流关闭失败");
            }
        }
        return false;
    }

    // 通过内容判断文件类型是否为XML
    public static boolean IsXmlDocByContextStr(String strFileContext) {
        InputStream stringInputStream = null;
        BufferedReader reader = null;
        StringBuilder builder = null;
        try {
//            System.out.println(fileName);
            stringInputStream = new ByteArrayInputStream(strFileContext.getBytes());
            reader = new BufferedReader(new InputStreamReader(stringInputStream, StrEncoding));
            String row;
            if (!ObjectUtil.isBlank(row = reader.readLine())) {
//                System.out.println(row);
                if (row.substring(0, 5).equals("<?xml") && row.substring(row.length() - 2, row.length()).equals("?>")) {
                    reader.close();
                    stringInputStream.close();
                    return true;
                }
            }
            reader.close();
            stringInputStream.close();
        } catch (Exception e) {
            logger.error("IsXmlDocByContext异常！");
        } finally {
            try {
                if (reader != null) reader.close();
                if (stringInputStream != null) stringInputStream.close();
            } catch (IOException ex) {
                logger.error("IsXmlDocByContext:流关闭失败");
            }
        }
        return false;
    }

    // 通过文件扩展名判断文件是不是配置的文件类型
    public static boolean IsTargetDocByFileName(File file,String fileTypes[]) {
        String name = file.getName();
        boolean isThisType=false;
        for (int i = 0; i < fileTypes.length; i++) {
            if (name.trim().toLowerCase().endsWith(fileTypes[i])) {
                isThisType=true;
            }
        }
        return  isThisType;
    }

    // 通过文件扩展名判断文件是不是配置的文件类型
    public static boolean IsTargetDocByFileName(String fileName,String fileTypes[]) {
        boolean isThisType=false;
        for (int i = 0; i < fileTypes.length; i++) {
            if (fileName.trim().toLowerCase().endsWith(fileTypes[i])) {
                isThisType=true;
            }
        }
        return  isThisType;
    }

    // 通过文件名判断是否是grib2数据
    public static boolean IsGrib2DocByFileName(File file) {
        String name = file.getName();
        if (!name.trim().toLowerCase().contains(".grib2")) {
//            System.out.println("非.txt文件");
            return false;
        } else {
            return true;
        }
    }


    public static boolean MoveFile(File oldFile, String strNewPath) {
        //new一个新文件夹
        File fnewpath = new File(strNewPath);
        //判断文件夹是否存在
        if (!fnewpath.exists()) {
            fnewpath.mkdirs();
        }
        if ('/' != strNewPath.charAt(strNewPath.length() - 1) || '\\' != strNewPath.charAt(strNewPath.length() - 1)) {
            strNewPath = strNewPath + '/';
        }

        //将文件移到新文件里
        File fnew = new File(strNewPath + oldFile.getName());
        //文件重命名失败（eg：该文件名已存在）
        if (!oldFile.renameTo(fnew)) {
            return false;
        }
        return true;
    }

    // strOldFilePath : 源文件包含路径的文件全名
    // strNewPath : 剪切后的目标目录
    public static boolean MoveFile(String strOldFilePath, String strNewPath) {
        //文件原地址
        File oldFile = new File(strOldFilePath);
        //new一个新文件夹
        File fnewpath = new File(strNewPath);
        //判断文件夹是否存在
        if (!fnewpath.exists())
            fnewpath.mkdirs();
        if ('/' != strNewPath.charAt(strNewPath.length() - 1) || '\\' != strNewPath.charAt(strNewPath.length() - 1)) {
            strNewPath = strNewPath + '/';
        }

        //将文件移到新文件里
        File fnew = new File(strNewPath + oldFile.getName());
        oldFile.renameTo(fnew);
        return true;
    }
}
